/**
 * webview uniapi兼容对象
 * 主要负责接受网页的调用uniapp api的请求，在调用完成后再反馈给网页结果
 * @author xueyanjun
 */
class XWebviewUni {
	
	/**
	 * 当被xwbridge安装时调用
	 * @param {Object} xwbridge webview通信对象
	 */
	static $onBridgeInstall(XWebview){
		this.$bridgeMessageTypes = ['uniapi','uniapi-ack'];
		this.$eventCallback = new Map();
		this.$onBridgeMessage = (data,xwvInstance)=>{
			// 调用uniapp的通用api
			const method = data.me;
			const options = data.op;
			const successfn = options.success;
			const failfn = options.fail;
			const completefn = options.complete;
			if(successfn){
				options.success = (res)=>{
					xwvInstance._postMsg({a:'uniapi-ack',d:{fn:successfn,res:res}});
				}
			}
			if(failfn){
				options.fail = (res)=>{
					xwvInstance._postMsg({a:'uniapi-ack',d:{fn:failfn,res:res}});
				}
			}
			if(completefn){
				options.complete = (res)=>{
					xwvInstance._postMsg({a:'uniapi-ack',d:{fn:completefn,res:res}});
				}
			}
			
			if(method === '$emit'){
				uni.$emit(options.name,...options.params);
				return;
			}
			if(method === '$on'){
				this.$eventCallback.set(successfn,options.success);
				uni.$on(options.name,options.success);
				return;
			}
			if(method === '$once'){
				uni.$once(options.name,options.success);
				return;
			}
			if(method === '$off'){
				const callback = this.$eventCallback.get(successfn);
				if(callback){
					uni.$off(options.name,callback);
				}
				return;
			}
			if(method === 'getSystemSetting'){
				const res = uni[method]();
				options.success(res);
				options.complete(res)
				return;
			}
			
			uni[method](options);
			
			return null;
		}
	}
}

export default XWebviewUni;